﻿using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace PickGold.SqlServer
{
	/// <summary>
	/// Triggers
	/// </summary>
	public partial class Triggers
	{
		/// <summary>
		/// Trigger
		/// </summary>
		[SqlTrigger]//(Name = "Trigger", Target = "Table", Event = "FOR UPDATE")
		public static void Trigger()
		{
			// 用您的代码替换
			SqlContext.Pipe.Send("Trigger FIRED:" + SqlContext.TriggerContext.TriggerAction);

			using (var con = Common.OpenConnection(null))
			{
				using (var cmd = con.CreateCommand())
				{
					cmd.CommandText = "select *, 'inserted' [inserted] from [inserted] for xml auto;";//, xmldata
					//SqlContext.Pipe.ExecuteAndSend(cmd);
					var t = string.Empty;
					var xdr = cmd.ExecuteXmlReader();
					while (xdr.Read())
						t += xdr.ReadOuterXml();
					xdr.Close();
					SqlContext.Pipe.Send(t);
					cmd.CommandText = "select *, 'deleted' [deleted] from [deleted] for xml auto;";//, xmldata
					//SqlContext.Pipe.ExecuteAndSend(cmd);
					t = string.Empty;
					xdr = cmd.ExecuteXmlReader();
					while (xdr.Read())
						t += xdr.ReadOuterXml();
					xdr.Close();
					SqlContext.Pipe.Send(t);
				}
				Common.CloseConnection(con, null);
			}

			if (SqlContext.TriggerContext.TriggerAction == TriggerAction.Insert)
			{
			}
			if (SqlContext.TriggerContext.ColumnCount > 0)
			{
			}
			if (SqlContext.TriggerContext.EventData == null)
			{
				SqlContext.Pipe.Send("SqlContext.TriggerContext.EventData is null.");
				return;
			}

			if (SqlContext.TriggerContext.EventData.IsNull)
			{
				SqlContext.Pipe.Send("SqlContext.TriggerContext.EventData.IsNull");
				return;
			}

			//if (SqlContext.TriggerContext.EventData.CreateReader() != null)
			//{
			//}
			if (string.IsNullOrEmpty(SqlContext.TriggerContext.EventData.Value))
			{
				SqlContext.Pipe.Send(SqlContext.TriggerContext.EventData.Value);
			}
			if (SqlContext.TriggerContext.IsUpdatedColumn(0))
			{
			}
		}
	}
}
